/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commands;

import entityclasses.Session;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import entityclasses.Group;
import factories.ObjectFactory;

/**
 *
 * @author umutcan
 */
public class AddGroupCommand implements GroupCommand {
    
    
 private String groupName;
    
    public AddGroupCommand(String groupName)
    {
        this.groupName = groupName;
    }
    
    @Override
    public void execute(JTree treeGruplar)
    {
        DefaultTreeModel dtm = (DefaultTreeModel)treeGruplar.getModel();
        TreePath tp = treeGruplar.getSelectionPath();
        
        Group newGroup = (Group)ObjectFactory.create(Group.class);
        
        newGroup.setName(groupName);
        
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode)tp.getLastPathComponent();
        
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newGroup);
        dtm.insertNodeInto(newNode, (DefaultMutableTreeNode)parent, 0);
        
        if (parent.isRoot())
            Session.currentUser.getProfile().addGroup(newGroup);
        else
           ((Group) parent.getUserObject()).addSubGroup(newGroup);
    }
}
